//
//  BaseViewController.m
//  BaseFrame
//
//  Created by apple on 16/9/28.
//  Copyright © 2016年 com.mxh. All rights reserved.
//

#import "BaseViewController.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <sys/utsname.h>
@interface BaseViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic,copy) void(^selectPhotoHandle)(UIImage *img);

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //布局 不延伸
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    
//    //设置导航栏 底线颜色
//    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:getColor(dividerColor)]];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setTranslucent:NO];
//
//    [self.view setBackgroundColor:[UIColor whiteColor]];
//    //导航栏背景颜色
//    [self.navigationController.navigationBar setBarTintColor:getColor(whiteColor)];
//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
//    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
//    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
//
//    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;// UIBarStyleBlack;
//    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:getColor(textColor3)};
    
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];  // 设置渐变效果
//    gradientLayer.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 64);
//    gradientLayer.position = CGPointMake(SCREEN_WIDTH/ 2, 32);
//    gradientLayer.colors = [NSArray arrayWithObjects:(id)[getColor(@"468df2") CGColor],(id)[getColor(@"5abcf9") CGColor], nil];
//    gradientLayer.startPoint = CGPointMake(0, 0.5);
//    gradientLayer.endPoint = CGPointMake(1.0, 0.5);
//    [[[self.navigationController.navigationBar.subviews firstObject] layer] addSublayer:gradientLayer];
    
    
    //导航栏背景颜色
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    //状态栏字体颜色
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    //导航栏标题字体颜色、大小属性
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    //设置导航栏背景
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //当为NO的时候，导航栏左下角为控制器view的（0，0）
    self.navigationController.navigationBar.translucent = NO;
    //返回按钮颜色
    [self.navigationController.navigationBar setTintColor:getColor(@"868686")];
//    [self.navigationController.navigationBar setTintColor:[UIColor redColor]];
//    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    //设置导航栏 底线颜色
//    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:getColor(borderColor)]];
    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:[UIColor clearColor]]];

    // 改变左右buttonItem样式
    NSDictionary* normalAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIColor blackColor],NSForegroundColorAttributeName,
                                      [UIFont systemFontOfSize:14],NSFontAttributeName,
                                      nil];
    [[UIBarButtonItem appearance] setTitleTextAttributes:normalAttributes forState:UIControlStateNormal];
    
    
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    
    self.navigationItem.backBarButtonItem = backItem;
    self.view.backgroundColor = [UIColor whiteColor];
    
}

- (MBProgressHUD *)progressHUD {
    if (!_progressHUD) {
        _progressHUD = [[MBProgressHUD alloc]initWithView:self.view];
        //        _progressHUD.frame = [UIScreen mainScreen].bounds;
        //        _progressHUD.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75];
    }
    return _progressHUD;
}

#pragma mark - Custom Method


/**
 *  显示错误的code码和信息
 *
 *  @param status    返回的code码
 *  @param message 返回的信息
 */
- (void) failureWithStatus:(NSString*)status message:(NSString*)message{
    NSLog(@"status:%@,msg:%@", status,message);
}

/**
 *  显示错误信息
 *
 *  @param error 返回的错误信息
 */
- (void) showError:(NSError*)error{
    switch (error.code) {
        case NSURLErrorNotConnectedToInternet:
            ShowMessage(@"请检查你的网络");
            break;
        case NSURLErrorTimedOut:
            ShowMessage(@"请求超时，请查看你的网络");
            break;
        case NSURLErrorCannotConnectToHost:
            ShowMessage(@"服务器繁忙，请稍后重试");
            break;
        case NSURLErrorNetworkConnectionLost:
            ShowMessage(@"处理过程中网络中断，请重试");
            break;
        default:
            ShowMessage(@"未知错误");
            break;
    }
}

/**
 *  显示大菊花
 */
-(void)showprogressHUD{
    self.tabBarController.view.userInteractionEnabled = NO;
    self.navigationController.view.userInteractionEnabled = NO;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self.navigationController.view addSubview:self.progressHUD];
    [self.progressHUD showAnimated:YES];
}

/**
 *  隐藏大菊花
 */
-(void)hiddenProgressHUD{
    self.tabBarController.view.userInteractionEnabled = YES;
    self.navigationController.view.userInteractionEnabled = YES;
    [self.progressHUD hideAnimated:YES];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.progressHUD removeFromSuperview];
}

/**
 弹出提示框 选择相机或者相册
 
 @param selectPhotoHandle 选中或拍摄的图片
 */
- (void)selectPhotoAlbumWithSelectPhotoHandle:(void (^)(UIImage *))selectPhotoHandle{
    self.selectPhotoHandle = selectPhotoHandle;
    
    UIAlertController *av = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [av addAction:action1];
    [av addAction:action2];
    [av addAction:cancelAction];
    [self presentViewController:av animated:YES completion:nil];
}

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    if (self.selectPhotoHandle) {
        self.selectPhotoHandle(image);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

/**
 *  拨打电话
 *
 *  @param phoneNumber 号码
 */
- (void)callPhone:(NSString *)phoneNumber{
    UIAlertController *av = [UIAlertController alertControllerWithTitle:phoneNumber message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [av addAction:action1];
    [av addAction:action2];
    [self presentViewController:av animated:YES completion:nil];
}

//设置状态栏颜色(透明)
- (void)setStatusBarBackgroundColor:(UIColor *)color withAlpha:(CGFloat)alpha{
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    //    UIView *statusBar = [[self valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
        statusBar.alpha = alpha;
    }
}
//设置状态栏颜色(不透明)
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;

    }
}

//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}
//获取手机型号
- (NSString *)iphoneType {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    if ([platform  isEqualToString:@"iPhone10,1"]) return@"iPhone 8";
    if ([platform  isEqualToString:@"iPhone10,4"]) return@"iPhone 8";
    if ([platform  isEqualToString:@"iPhone10,2"]) return@"iPhone 8 Plus";
    if ([platform  isEqualToString:@"iPhone10,5"]) return@"iPhone 8 Plus";
    if ([platform  isEqualToString:@"iPhone10,3"]) return@"iPhone X";
    if ([platform  isEqualToString:@"iPhone10,6"]) return@"iPhone X";
    return platform;
}
#pragma mark - method
- (void)label:(UILabel *)label withFont:(UIFont *)font withText:(NSString *)text withTextColor:(UIColor *)color withTextAlignment:(NSTextAlignment)textAlignment withView:(UIView *)upSuperView withBGColor:(UIColor *)bgColor{
    label.textAlignment = textAlignment;
    label.font = font;
    label.textColor = color;
    label.text = text;
    label.backgroundColor = bgColor;
    [upSuperView addSubview:label];
}
- (void)button:(UIButton *)btn withBGColor:(UIColor *)color withLayerBorderColor:(UIColor *)borderColor withLayerBorderWith:(CGFloat)borderWith withCornerRadius:(CGFloat)cornerRadius withMasksToBounds:(BOOL)masksToBounds withViwe:(UIView *)upSuperView{
    [btn setBackgroundColor:color];
    btn.layer.borderColor = borderColor.CGColor;
    btn.layer.borderWidth = borderWith;
    btn.layer.cornerRadius = cornerRadius;
    btn.layer.masksToBounds = cornerRadius;
    [upSuperView addSubview:btn];
}
- (void)view:(UIView *)view withBackgroundColor:(UIColor *)backgroundColor withBorderColor:(UIColor *)borderColor withBorderWidth:(CGFloat)borderWith withCornerRadius:(CGFloat)cornerRadius withMasksToBounds:(BOOL)masksToBounds withSuperView:(UIView *)superView{
    view.backgroundColor = backgroundColor;
    view.layer.borderColor = borderColor.CGColor;
    view.layer.borderWidth = borderWith;
    view.layer.cornerRadius = cornerRadius;
    view.layer.masksToBounds = masksToBounds;
    [superView addSubview:view];
}
//首字母就是数字的
- (void)changeStringTypeface:(NSString *)string withFirstLoc:(NSInteger)firstLoc withSecondLocStr:(NSString *)secondLocStr withLabel:(UILabel *)label{
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:string];
    //     需要改变的最后一个文字的位置
    NSUInteger secondLoc = [[noteStr string] rangeOfString:secondLocStr].location;
    // 需要改变的区间
    NSRange range = NSMakeRange(firstLoc, secondLoc - firstLoc);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:range];
    [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:18] range:range];
    [label setAttributedText:noteStr];
}
//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11){
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}
@end
